<!-- /src/components/TrendLineChart.vue
作用：渲染“支付金额 / 退款金额 / 千川消耗”的折线图，并支持多选显示多条折线
输入：
  - title: 标题
  - lineData: 来自接口的对象结构（key 为指标名，value 为按日期的对象映射：{ 'yyyy-mm-dd': { value: '123.45' } }）
  - dateList: 对齐后的日期数组（包含完整连续日期，缺失数据前端补 0）
说明：
  lineData 数据结构参考你的示例：
    {
      yong_hu_zhi_fu_price: {'2025-10-01': {value: 'xxx'}, ...},
      tui_kuan_price:       {'2025-10-01': {value: 'xxx'}, ...},
      qian_chuan_cost:      {'2025-10-01': {value: 'xxx'}, ...}
    }
  对应中文名（你的文档定义）：
    yong_hu_zhi_fu_price: 支付金额
    tui_kuan_price:       退款金额
    qian_chuan_cost:      千川消耗
引用字段释义：见:contentReference[oaicite:8]{index=8}
-->

<template>

    <!--   折线图    -->
    <div >

        <!-- 开关按钮 -->
        <div class="legend-toggle">

            <el-button
                    v-for="line in trendLines"
                    :key="line.key"
                    size="small"
                    @click="toggleLine(line.key)"
                    :style="{
                    backgroundColor: line.visible ? colorMap[line.key] : '#fff',
                    borderColor: colorMap[line.key],
                    color: line.visible ? '#fff' : colorMap[line.key]
                  }"
            >
                {{ line.label }}
            </el-button>

        </div>

        <!-- ECharts -->
        <div class="chart-scroll-container">
            <div ref="chartRef" class="trend-chart"></div>
        </div>
    </div>
</template>

<script setup>
    import {ref, computed, onMounted, watch } from "vue";
    import dayjs from "dayjs"
    import * as echarts from "echarts"

    const isMobile = computed(() => window.innerWidth <= 768);




    const colorMap = {
        pay: "#4472c4",      // 支付金额 蓝色
        refund: "#70ad47",   // 退款金额 深灰
        discount: "#ed7d31"  // 千川消耗 青黄
    }

    const chartRef = ref(null)
    let chartInstance = null

    const month = ref(dayjs().format("YYYY-MM"))

    const trendLines = ref([
        { key: "pay", label: "支付金额", visible: true },
        { key: "refund", label: "退款金额", visible: false },
        { key: "discount", label: "千川消耗", visible: false }
    ])

    // 模拟数据结构
    // const trendData = ref({})

    const props = defineProps({
        trendData: { type: Object, default: () => ({}) }
    })

    watch(() => props.trendData, () => {
        renderChart()
    }, { deep: true })

    onMounted(() => {
        renderChart()
    })

    const toggleLine = (key) => {

        const line = trendLines.value.find(l => l.key === key)
        line.visible = !line.visible
        renderChart()   // 用新的渲染函数
    }




    const renderChart = () => {
        if (!chartInstance) {
            chartInstance = echarts.init(chartRef.value)
            window.addEventListener('resize', () => chartInstance && chartInstance.resize())
        }

        const visible = trendLines.value.filter(l => l.visible)

        // 自动计算所有值的最大值
        const allValues = []
        for (const l of visible) {
            if (Array.isArray(props.trendData[l.key])) {
                allValues.push(...props.trendData[l.key])
            }
        }
        const maxVal = Math.max(...allValues.filter(v => !isNaN(v)), 0)
        const axisMax = Math.ceil(maxVal / 10000) * 10000

        const option = {
            tooltip: {
                trigger: 'axis',
                textStyle: { fontSize: 14 },
                formatter: params => {
                    const date = params[0]?.axisValue || ''
                    const lines = params.map(p => `
          <span style="display:inline-block;width:10px;height:10px;
            border-radius:50%;background:${colorMap[p.seriesId]};
            margin-right:6px;"></span>
            ${p.seriesName}：${formatNumber(p.data)} 元`
                    )
                    return `<div style="margin-bottom:5px;font-weight:bold;">${date}</div>${lines.join('<br/>')}`
                }
            },
            grid: { top: 50, left: 50, right: 50, bottom: 30 },
            xAxis: {
                type: "category",
                data: props.trendData.days,
                axisLine: { show: true },
                axisTick: { show: true },
                axisLabel: { show: true },
                splitLine: { show: false }
            },
            // ✅ 所有折线共用一个Y轴
            yAxis: [{
                type: "value",
                scale: true,
                max: axisMax,
                axisLabel: {
                    formatter: val => val >= 10000 ? (val / 10000).toFixed(1) + "万" : val
                },
                splitLine: {
                    show: true,
                    lineStyle: {
                        color: "rgba(0,0,0,0.1)",
                        type: "dotted"
                    }
                }
            }],
            series: visible.map(l => ({
                id: l.key,
                name: l.label,
                type: 'line',
                data: props.trendData[l.key],
                smooth: true,
                showSymbol: false,
                symbolSize: 6,
                lineStyle: {
                    width: 3,
                    color: colorMap[l.key]
                }
            }))
        }

        chartInstance.setOption(option, { notMerge: true, lazyUpdate: false })
    }


    function formatNumber(value) {
        if (value >= 10000) {
            return (value / 10000).toFixed(2).replace(/\.00$/, '') + '万'
        }
        return value.toLocaleString('zh-CN')
    }




</script>

<style scoped>

    .el_date_picker{
        height: 60px;
    }
    .trend-chart {
        width: 100%;
        height: 360px;
        margin-top: 20px;
        background: #fff;
    }





    .legend-toggle {
        margin-bottom: 12px;
        margin-top: 30px;
    }

    .legend-toggle .el-button {
        margin-right: 10px;
        height: 35px;
        width: 100px;
        font-size: 16px;
    }



    /* 手机适配 */
    @media (max-width: 768px) {

        /* 按钮网格：每行 2 个，行列间距一致 */
        .legend-toggle{
            width: 100%;
            display: grid;
            grid-template-columns: repeat(2, minmax(0, 1fr)); /* 每行2列，列可压缩 */
            column-gap: 10px;
            row-gap: 10px;
            margin-top: 10px;

            /* 关键：避免最后一行项目被“分散对齐” */
            justify-content: start;   /* 网格整体靠左 */
            align-content: start;     /* 网格行从上往下堆叠 */
            justify-items: stretch;   /* 单元格内子项拉满 */
            align-items: center;      /* 子项垂直居中 */
        }

        /* 子按钮填满各自网格，不要再用 flex/min-width */
        .legend-toggle > .el-button{
            width: 100%;
            margin: 0;                /* 防止默认 margin 影响对齐 */
            box-sizing: border-box;
        }

        /* ✅ 折线图容器横向滑动 */
        .trend-chart {
            width: 1200px; /* 超出手机宽度，支持滑动查看 */
            max-height: 300px;
        }

        /* ✅ 滑动外层容器 */
        .chart-scroll-container {
            width: 100%;
            overflow-x: auto;
            overflow-y: hidden;
            margin-top: 10px;
        }
    }

    @media (max-width: 480px) {

    }
</style>
